<template>
    <div class="app-container">
        <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch">
            <el-form-item label="快站账号" prop="account">
                <el-input v-model.trim="queryParams.account" placeholder="请输入快站账号" clearable style="width: 240px"
                          @keyup.enter.native="handleQuery" />
            </el-form-item>
            <el-form-item label="创建时间">
                <el-date-picker v-model="dateRange" style="width: 240px"
                value-format="yyyy/MM/dd" 
                type="daterange"
                range-separator="-" start-placeholder="开始日期" end-placeholder="结束日期"></el-date-picker>
            </el-form-item>
            <el-form-item>
                <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
                <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
            </el-form-item>
            <el-form-item>
                <el-button type="primary" plain icon="el-icon-plus" size="mini" @click="handleAdd"
                           v-hasPermi="['kzManage:account:add']">新增</el-button>
            </el-form-item>
        </el-form>

        <el-row :gutter="10" class="mb8" v-if="false">
            <el-col :span="1.5">
                <el-button type="primary" plain icon="el-icon-plus" size="mini" @click="handleAdd"
                           v-hasPermi="['kzManage:account:add']">新增</el-button>
            </el-col>
            <el-col :span="1.5">
                <el-button type="warning" plain icon="el-icon-download" size="mini" @click="handleExport"
                           v-hasPermi="['system:role:export']">导出</el-button>
            </el-col>
            <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
        </el-row>

        <el-table v-loading="loading" :data="roleList">
            <el-table-column type="index" width="55" align="center">
                <template slot-scope="scope">
                    {{ (queryParams.pageNum - 1) * queryParams.pageSize + scope.$index + 1 }}
                </template>
            </el-table-column>
            <el-table-column label="快站账号" prop="account" width="150" />
            <el-table-column label="密码" prop="password" width="200">
                <template slot-scope="scope">
                    <el-input show-password v-model="scope.row.password" onfocus="this.blur()"/>
                </template>
            </el-table-column>
            <el-table-column label="站点数量" prop="siteCount" width="80" />
            <el-table-column label="APP_KEY" prop="appKey" :show-overflow-tooltip="true" width="150" />
            <el-table-column label="APP_SECRET" prop="appSecret" min-width="200" >
                <template slot-scope="scope">
                    <el-input  type="password" v-model="scope.row.appSecret" show-password onfocus="this.blur()"/>
                </template>
            </el-table-column>

            <el-table-column label="创建时间" align="center" prop="createTime" width="180">
                <template slot-scope="scope">
                    <span>{{ parseTime(scope.row.createTime) }}</span>
                </template>
            </el-table-column>
            <el-table-column label="备注" prop="remark" min-width="150" />
            <el-table-column label="操作" align="center" class-name="small-padding fixed-width" fixed="right" width="280">
                <template slot-scope="scope" v-if="scope.row.roleId !== 1">
                    <el-button size="mini" type="text" icon="el-icon-edit" @click="handleUpdate(scope.row)"
                               v-hasPermi="['system:role:edit']">修改</el-button>
                    <el-button size="mini" type="text" icon="el-icon-refresh" @click="handleSyncSite(scope.row)"
                               v-hasPermi="['system:role:remove']">同步站点</el-button>
                    <el-button size="mini" type="text" icon="el-icon-position" @click="handleGoKzLogin(scope.row)"
                               v-hasPermi="['system:role:remove']">登录快站</el-button>
                </template>
            </el-table-column>
        </el-table>

        <pagination v-show="total > 0" :total="total" :page.sync="queryParams.pageNum"
                    :limit.sync="queryParams.pageSize" @pagination="getList" />

        <!-- 添加或修改账号对话框 -->
        <el-dialog :title="title" :visible.sync="open" width="500px" append-to-body>
            <el-form ref="form" :model="form" :rules="rules" label-width="120px">
                <el-form-item label="快站账号" prop="account">
                    <el-input v-model.trim="form.account" placeholder="请输入快站账号" :disabled="!!form.id"/>
                </el-form-item>
                <el-form-item label="账号密码" prop="password">
                    <el-input type="password" v-model.trim="form.password" placeholder="请输入快站账号密码" />
                </el-form-item>
                <el-form-item label="APP_KEY" prop="appKey">
                    <el-input v-model.trim="form.appKey" placeholder="请输入快站账号APP_KEY" />
                </el-form-item>
                <el-form-item label="APP_SECRET" prop="appSecret">
                    <el-input type="password" v-model.trim="form.appSecret" placeholder="请输入快站账号APP_SECRET" />
                </el-form-item>
                <el-form-item label="备注">
                    <el-input v-model="form.remark" type="textarea" placeholder="请输入内容"></el-input>
                </el-form-item>
            </el-form>
            <div slot="footer" class="dialog-footer">
                <el-button type="primary" @click="submitForm">确 定</el-button>
                <el-button @click="cancel">取 消</el-button>
            </div>
        </el-dialog>
    </div>
</template>

<script>
import { listRole, getRole, delRole, addRole, updateRole, dataScope, changeRoleStatus, deptTreeSelect } from '@/api/system/role';

import { addAccount } from '@/api/kzManage'
import { accountList, editAccount, syncAccount } from '../../api/kzManage'
import {Loading} from "element-ui";

export default {
    name: 'Account',
    dicts: ['sys_normal_disable'],
    data() {
        return {
            // 遮罩层
            loading: true,
            // 选中数组
            ids: [],
            // 非单个禁用
            single: true,
            // 非多个禁用
            multiple: true,
            // 显示搜索条件
            showSearch: true,
            showSecretAccount: '',
            // 总条数
            total: 0,
            // 角色表格数据
            roleList: [],
            // 弹出层标题
            title: '',
            // 是否显示弹出层
            open: false,
            // 日期范围
            dateRange: [],
            // 查询参数
            queryParams: {
                pageNum: 1,
                pageSize: 20,
                account: undefined,
            },
            // 表单参数
            form: {
                account: '',
                password: '',
                appKey: '',
                appSecret: '',
                remark: ''
            },
            defaultProps: {
                children: 'children',
                label: 'label',
            },
            // 表单校验
            rules: {
                account: [{ required: true, message: '账号不能为空', trigger: 'blur' }],
                password: [{ required: true, message: '账号密码不能为空', trigger: 'blur' }],
                appKey: [{ required: true, message: 'APP_KEY不能为空', trigger: 'blur' }],
                appSecret: [{ required: true, message: 'APP_SECRET不能为空', trigger: 'blur' }],
            },
        };
    },
    created() {
        this.getList();
    },
    methods: {
        /** 查询列表 */
        getList() {
            this.loading = true;
            let dateRange = Array.isArray(this.dateRange) ? this.dateRange : [];
            if(dateRange[0]) {
                dateRange[0] = this.dateRange[0]+' 00:00:00'
            }
            if(dateRange[1]) {
                dateRange[1] = this.dateRange[1]+' 23:59:59'
            } 
            accountList(this.addDateRange(this.queryParams, dateRange)).then((response) => {
                this.roleList = response.data.list;
                this.total = response.data.total;
            })
            .finally(() => {
                this.loading = false;
            });
        },
        // 取消按钮
        cancel() {
            this.open = false;
            this.reset();
        },
        // 取消按钮（数据权限）
        cancelDataScope() {
            this.openDataScope = false;
            this.reset();
        },
        // 表单重置
        reset() {
            (this.form = {
                    account: '',
                    password: '',
                    appKey: '',
                    appSecret: '',
                    remark: '',
                });
            this.resetForm('form');
        },
        /** 搜索按钮操作 */
        handleQuery() {
            this.queryParams.pageNum = 1;
            this.getList();
        },
        /** 重置按钮操作 */
        resetQuery() {
            this.dateRange = [];
            this.resetForm('queryForm');
            this.handleQuery();
        },
        // 更多操作触发
        handleCommand(command, row) {
            switch (command) {
                case 'handleDataScope':
                    this.handleDataScope(row);
                    break;
                case 'handleAuthUser':
                    this.handleAuthUser(row);
                    break;
                case 'handleSyncSite':
                    this.handleSyncSite(row);
                    break;
                default:
                    break;
            }
        },
        /** 新增按钮操作 */
        handleAdd() {
            this.reset();
            this.open = true;
            this.title = '添加账号';
        },
        /** 修改按钮操作 */
        handleUpdate(row) {
            this.reset();
            this.form = {
                ...row
            }
            const accountId = row.id
            this.title = '修改账号';
            this.open = true;
        },
        /** 提交按钮 */
        submitForm: function () {
            this.$refs['form'].validate((valid) => {
                if (valid) {
                    if (this.form.id != undefined) {
                        editAccount(this.form).then((response) => {
                            this.$modal.msgSuccess('修改成功');
                            this.open = false;
                            this.getList();
                        });
                    } else {
                        addAccount(this.form).then((response) => {
                            this.$modal.msgSuccess('新增成功');
                            this.open = false;
                            this.getList();
                        });
                    }
                }
            });
        },

        // 同步快站
        handleSyncSite(row) {
            let loadingInstance = Loading.service({ text: '正在同步中，请稍候', spinner: 'el-icon-loading', background: 'rgba(0, 0, 0, 0.7)' });
            syncAccount(row.id).then(res => {
                this.handleQuery()
                this.$message.success(`已同步成功${res.data.siteIds.length}个快站`)
            })
            .finally(() => {
                loadingInstance.close()
            })
        },
        //凯撒加密
        caesarEncrypt(text, shift) {
            let encryptedText = '';
            for (let i = 0; i < text.length; i++) {
                let charCode = text.charCodeAt(i);
                if (charCode >= 65 && charCode <= 90) {
                    // 大写字母
                    encryptedText += String.fromCharCode(((charCode - 65 + shift) % 26) + 65);
                } else if (charCode >= 97 && charCode <= 122) {
                    // 小写字母
                    encryptedText += String.fromCharCode(((charCode - 97 + shift) % 26) + 97);
                } else if (charCode >= 48 && charCode <= 57) {
                    // 数字字符
                    encryptedText += String.fromCharCode(((charCode - 48 + shift) % 10)+ 48);
                } else {
                    encryptedText += text.charAt(i);
                }
            }
            return encryptedText;
        },
        caesarDecrypt(encryptedText, shift) {
            let decryptedText = '';
            for (let i = 0; i < encryptedText.length; i++) {
                let charCode = encryptedText.charCodeAt(i);
                if (charCode >= 65 && charCode <= 90) {
                    // 大写字母
                    decryptedText += String.fromCharCode(((charCode - 65 - shift + 26) % 26)+ 65);
                } else if (charCode >= 97 && charCode <= 122) {
                    // 小写字母
                    decryptedText += String.fromCharCode(((charCode - 97 - shift + 26) % 26)+ 97);
                } else if (charCode >= 48 && charCode <= 57) {
                    // 数字字符
                    decryptedText += String.fromCharCode(((charCode - 48 - shift + 10) % 10)+ 48);
                } else {
                    decryptedText += encryptedText.charAt(i);
                }
            }
            return decryptedText;
        },

        handleGoKzLogin(row) {
            let shift =  Math.floor(Math.random() * 7) + 2;
            window.open(`https://www.kuaizhan.com/?mySecret=${shift}_${this.caesarEncrypt(row.account, shift)}_${this.caesarEncrypt(row.password, shift)}`, '_blank')
        }
    },
};
</script>
